package top.huxy.boot.service.impl;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.huxy.boot.controller.admin.AdminHomeController;
import top.huxy.boot.exception.RequestAbortedException;
import top.huxy.boot.exception.RequestParamIllegalException;
import top.huxy.boot.mapper.NavSiteMapper;
import top.huxy.boot.mapper.UserSaveSiteMapper;
import top.huxy.boot.model.dto.Pager;
import top.huxy.boot.model.entity.NavSite;
import top.huxy.boot.model.vo.VONavSite;
import top.huxy.boot.model.vo.user.VO_User;
import top.huxy.boot.service.NavSiteService;
import top.huxy.boot.service.VOUserService;

import java.util.LinkedList;
import java.util.List;

/**
 * (NavSite)表服务实现类
 *
 * @author HuXY
 * @since 2021-11-26 14:36:07
 */
@Service
public class NavSiteServiceImpl implements NavSiteService {

    @Autowired
    private NavSiteMapper navSiteMapper;

    @Autowired
    VOUserService voUserService;

    @Autowired
    UserSaveSiteMapper userSaveSiteMapper;

    @Override
    public List<VONavSite> getNavSiteList() {
        List<VONavSite> list = navSiteMapper.getNavSiteList();
        if (list == null) {
            list = new LinkedList<>();
        }
        for (VONavSite voNavSite : list) {
            List<VONavSite.NavItem> navs = voNavSite.getNavs();
            if (navs != null && navs.size() == 1 && navs.get(0).getId() == null) {
                navs.clear();
            } else {
                for (VONavSite.NavItem nav : navs) {
                    if (nav.getDesc() == null) {
                        nav.setDesc("");
                    }
                }
            }
        }
        VONavSite noGroupNavSite = navSiteMapper.getNoGroupNavSite();
        if (noGroupNavSite != null) {
            list.add(noGroupNavSite);
        }
        return list;
    }

    @Override
    public void insert(AdminHomeController.DTOSite site) {
        site.validate();
        int navSiteCount = navSiteMapper.getNavCountByName(site.getGrp());
        if (navSiteCount == 0) {
            navSiteMapper.insertSiteGroup(site.getGrp());
        }

        site.setGrp(navSiteMapper.getGrpIdByName(site.getGrp()));
        Integer w = navSiteMapper.getMaxItemWeight(Integer.parseInt(site.getGrp()));
        //新增的是默认最大的权重
        if (w != null) {
            site.setWeight(w + 1);
        } else {
            site.setWeight(0);
        }
        navSiteMapper.insert(site);
    }

    @Override
    public void updateSiteGroup(AdminHomeController.DTOEditGroup dtoEditGroup) {
        dtoEditGroup.validate();
        int res = navSiteMapper.updateSiteGroup(dtoEditGroup);
        if (res == 0) {
            throw new RequestAbortedException("未修改数据");
        }
        if (res > 1) {
            throw new RequestAbortedException("不在预期的结果");
        }
    }

    @Override
    public void updateSite(AdminHomeController.DTOSite site) {
        site.validate();
        Integer id = site.getId();
        if (id == null) {
            throw new RequestParamIllegalException("id is null");
        }

        int navSiteCount = navSiteMapper.getNavCountByName(site.getGrp());
        if (navSiteCount == 0) {
            navSiteMapper.insertSiteGroup(site.getGrp());
        }
        site.setGrp(navSiteMapper.getGrpIdByName(site.getGrp()));

        int res = navSiteMapper.updateSite(site);
        if (res == 0) {
            throw new RequestAbortedException("未修改数据");
        }
        if (res > 1) {
            throw new RequestAbortedException("不在预期的结果");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void moveGroup(String grp, String target, String type) {
        if ("after".equals(type)) {
            //获取目标权重
            Integer targetWeight = navSiteMapper.getGroupWeightByName(target);
            //把大于等于目标权重的都+1

            navSiteMapper.increaseGroupWeightWhereGreaterOrEqual(targetWeight);
            //让自己变成目标权重
            navSiteMapper.setGroupWeightByGrp(grp, targetWeight);

        } else if ("before".equals(type)) {
            //获取目标权重
            Integer targetWeight = navSiteMapper.getGroupWeightByName(target);
            //把大于目标权重的都+1
            navSiteMapper.increaseGroupWeightWhereGreaterOrEqual(targetWeight);
            //让自己变成目标权重+1
            navSiteMapper.setGroupWeightByGrp(grp, targetWeight + 1);
        } else {
            throw new RequestParamIllegalException("illegal type : " + type);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void moveItem(Integer item, Integer target, String type) {
        if ("after".equals(type)) {
            if (target == null) {
                throw new RequestParamIllegalException("target must not is null when type is `after`");
            }
            NavSite navTarget = navSiteMapper.getItemById(target);
            Integer targetWeight = navTarget.getWeight();
            //把大于等于目标权重的都+1
            navSiteMapper.increaseItemWeightWhereGreaterOrEqual(navTarget.getGrp(), targetWeight);
            //让自己变成目标权重
            navSiteMapper.setItemWeightAndGrpById(item, navTarget.getGrp(), targetWeight);
        } else if ("before".equals(type)) {
            if (target == null) {
                throw new RequestParamIllegalException("target must not is null when type is `before`");
            }
            NavSite navTarget = navSiteMapper.getItemById(target);
            Integer targetWeight = navTarget.getWeight();
            //把大于目标权重的都+1
            navSiteMapper.increaseItemWeightWhereGreater(navTarget.getGrp(), targetWeight);
            //让自己变成目标权重+1
            navSiteMapper.setItemWeightAndGrpById(item, navTarget.getGrp(), targetWeight + 1);
        } else if ("inner".equals(type)) {
            //target是组id
            Integer w = navSiteMapper.getMinItemWeight(target);
            if (w == null) {
                navSiteMapper.setItemWeightAndGrpById(item, target, 10);
            } else {
                navSiteMapper.setItemWeightAndGrpById(item, target, w - 1);
            }
        } else {
            throw new RequestParamIllegalException("illegal type : " + type);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delSiteGroup(Integer id) {
        navSiteMapper.clearItemGroup(id);
        int res = navSiteMapper.delSiteGroup(id);
        if (res == 0) {
            throw new RequestAbortedException("未删除数据");
        }
        if (res > 1) {
            throw new RequestAbortedException("不在预期的结果");
        }
    }

    @Override
    public void delSite(Integer id) {
        int res = navSiteMapper.delSite(id);
        if (res == 0) {
            throw new RequestAbortedException("未删除数据");
        }
        if (res > 1) {
            throw new RequestAbortedException("不在预期的结果");
        }
    }

    @Override
    public void saveHistorySite(Integer id, String userToken) {
        //获取用户
        VO_User user = voUserService.getVOUserByToken(userToken);
        if (user == null) {
            throw new RequestAbortedException("缺少凭证");
        }

        String userId = user.getId();
        userSaveSiteMapper.insert(id, userId, System.currentTimeMillis());
    }

    @Override
    public List<VONavSite.NavItem> getHistorySite(Pager pager, String userToken) {
        //获取用户
        VO_User user = voUserService.getVOUserByToken(userToken);
        if (user == null) {
            throw new RequestAbortedException("缺少凭证");
        }
        try {
            PageHelper.startPage(pager.getPage(), pager.getPageSize(), "uss.create_time desc");
            return userSaveSiteMapper.getHistorySite(user.getId());
        } finally {
            PageHelper.clearPage();
        }
    }

    @Override
    public void removeAllHistory(String userToken) {
        //获取用户
        VO_User user = voUserService.getVOUserByToken(userToken);
        if (user == null) {
            throw new RequestAbortedException("缺少凭证");
        }
        userSaveSiteMapper.removeAllHistory(user.getId());
    }

    @Override
    public void removeSiteById(String userToken, String ids) {
        //获取用户
        VO_User user = voUserService.getVOUserByToken(userToken);
        if (user == null) {
            throw new RequestAbortedException("缺少凭证");
        }
        String[] split = ids.split(",");
        LinkedList<Integer> idList = new LinkedList<>();
        for (String s : split) {
            idList.add(Integer.valueOf(s));
        }
        userSaveSiteMapper.removeSiteById(user.getId(), idList);
    }
}
